import React, { useState, useEffect, useCallback } from 'react';
import { Space, Button, Table, Modal, message } from 'antd';
import './style.scss';
import Search from 'antd/lib/input/Search';
import { InterfacesInfo } from 'admin/schema/BasicResource';
import { ColumnsType } from 'antd/es/table/interface';
import { getInterfacesList, deleteInterfaces } from 'admin/servers/servers';
import { OperateInterface } from '../../OperateInterface';
import moment from 'moment';
import { deleteRowChangePageNum } from 'utils/tools';

const Interfaces: React.FC<{ versionId: number }> = props => {
  const { versionId } = props;
  // Table loading状态
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  // 当前页码
  const [current, setCurrent] = useState<number>(1);
  // 每页条数
  const [pageSize, setPageSize] = useState<number>(10);
  //  数据总数
  const [total, setTotal] = useState<number>(0);
  // Table数据
  const [interfacesList, setInterfacesList] = useState<InterfacesInfo[]>([]);
  // 搜索内容
  const [searchText, setSearchText] = useState<string>('');

  // 删除：弹框显示
  const [deleteVisible, setDeleteVisible] = useState<boolean>(false);
  // 删除：接口ID
  const [deleteInterfaceId, setDeleteInterfaceId] = useState<number>(0);
  // 删除：确认按钮loading
  const [confirmDeleteLoading, setConfirmDeleteLoading] = useState<boolean>(false);
  // 编辑：接口ID
  const [modifyInterfaceId, setModifyInterfaceId] = useState<number>(0);

  // 新增/编辑：弹框显示
  const [createVisible, setCreateVisible] = useState<boolean>(false);

  // 每列配置
  const columns: ColumnsType<InterfacesInfo> = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (text, record, index) => index + 1 + pageSize * (current - 1),
    },
    {
      title: '接口名称',
      dataIndex: 'interfaceName',
      key: 'interfaceName',
    },
    {
      title: '请求方式',
      dataIndex: 'callMode',
      key: 'callMode',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: text => moment(Number(text)).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            onClick={() => {
              modifyInterfacesAction(index);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            onClick={() => {
              deleteInterfacesAction(index);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  /**
   * Table数据加载
   */
  const initData = useCallback(async () => {
    setTableLoading(true);
    try {
      const res = await getInterfacesList({
        versionId,
        pageNo: current,
        pageSize: pageSize,
        interfaceName: searchText,
      });
      if (res.code === 0) {
        setInterfacesList(res.data || []);
        setTotal(Number(res.count) || 0);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setTableLoading(false);
  }, [current, pageSize, searchText, versionId]);

  // 数据初始化 && 数据更新
  useEffect(() => {
    initData();
  }, [initData]);

  /**
   * 对table数据进行刷新：新增，编辑
   * @param pageNum 刷新页码
   */
  const refreshTable = async (pageNum?: number) => {
    if (pageNum) {
      current === pageNum ? initData() : setCurrent(pageNum);
    } else {
      initData();
    }
  };

  /**
   * 对table数据进行刷新：删除
   */
  function deleteFresh(size: number) {
    const newPageNum = deleteRowChangePageNum(size, total, current, pageSize);
    refreshTable(newPageNum);
  }

  /**
   * 翻页
   * @param pageNo 点击页码
   */
  const onChagneCurrent = (pageNo: number) => {
    setCurrent(pageNo);
  };
  /**
   *改变每页显示条数
   * @param current 当前页码
   * @param pageSize 每页显示条数
   */
  const onChangePageSize = (current: number, pageSize: number) => {
    setPageSize(pageSize);
  };

  /**
   * 根据变量名称搜索
   * @param text 搜索内容
   */
  const searchVariables = (text: string) => {
    text = text.trim();
    if (text !== searchText) {
      setSearchText(text);
      setCurrent(1);
    }
  };

  /**
   * 编辑操作
   * @param idx 所编辑数据的index
   */
  const modifyInterfacesAction = (idx: number) => {
    console.log('编辑', idx);
    const { interfaceId } = interfacesList[idx];

    setModifyInterfaceId(interfaceId);
    setCreateVisible(true);
  };

  /**
   * 删除操作
   * @param idx 所删除数据的index
   */
  const deleteInterfacesAction = (idx: number) => {
    console.log('删除', idx);
    setDeleteInterfaceId(interfacesList[idx].interfaceId);
    setDeleteVisible(true);
  };

  /**
   * 请求删除变量接口
   * @param varId
   */
  const requestDeleteInterfaces = async (interfaceId: number) => {
    setConfirmDeleteLoading(true);
    try {
      const res = await deleteInterfaces({
        interfaceId,
      });
      if (res.code === 0) {
        message.success('删除成功');
        setDeleteVisible(false);
        deleteFresh(1);
      } else {
        message.error(`${res.tips}(错误码: ${res.code})`);
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }

    setConfirmDeleteLoading(false);
  };

  // 分页配置
  const pagination = {
    total: total,
    showTotal: (total: number) => `共 ${total} 条`,
    current: current,
    pageSize: pageSize,
    showSizeChanger: true,
    onChange: onChagneCurrent,
    onShowSizeChange: onChangePageSize,
  };

  return (
    <>
      <div className="basic-word-library-top">
        <Search
          placeholder="请输入接口名称"
          enterButton="搜索"
          style={{ width: 300 }}
          onSearch={searchVariables}
        />
        <div>
          <Space>
            <Button
              type="primary"
              onClick={() => {
                setModifyInterfaceId(0);
                setCreateVisible(true);
              }}
            >
              新建接口
            </Button>
          </Space>
        </div>
      </div>
      <div style={{ marginTop: 20 }} className="mgr-table">
        <Table
          loading={tableLoading}
          columns={columns}
          dataSource={interfacesList}
          rowKey="interfaceId"
          pagination={pagination}
        />
      </div>

      {/* 新建/编辑抽屉弹框组件 */}
      <OperateInterface
        versionId={versionId}
        interfaceId={modifyInterfaceId}
        show={createVisible}
        onClose={() => {
          setCreateVisible(false);
        }}
        onSuccess={() => {
          setCreateVisible(false);
          modifyInterfaceId ? refreshTable() : refreshTable(1);
        }}
      />

      {/* 删除弹框 */}
      <Modal
        title="删除接口提示"
        visible={deleteVisible}
        onOk={() => {
          requestDeleteInterfaces(deleteInterfaceId);
        }}
        confirmLoading={confirmDeleteLoading}
        onCancel={() => {
          setDeleteVisible(false);
        }}
      >
        <p>删除后无法恢复！确定删除吗？</p>
      </Modal>
    </>
  );
};

export default Interfaces;
